package com.project.web.controller;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.project.entity.BookType;

/**
 * @author travisl@synnex.com
 * 
 */
@Controller
@RequestMapping("/booktype")
public class BookTypeController extends GenericController {

	/**
	 * Forward to edit.jsp.
	 * 
	 * @return
	 */
	@RequestMapping(value = "/add")
	public String add() {
		return "booktype/edit";
	}

	/**
	 * Add or update book type.
	 * 
	 * @param bookType
	 * @return
	 */
	@RequestMapping(value = "/save")
	public String save(BookType bookType) {
		if (StringUtils.isBlank(bookType.getName())
				|| StringUtils.isBlank(bookType.getDescription())) {
			return "error";
		}
		if (bookType.getId() == null) {
			bookTypeService.saveOrUpdate(bookType);
		} else {
			bookTypeService.update(bookType);
		}

		return "redirect:/booktype/list";
	}

	/**
	 * Retrieve all book type.
	 * 
	 * @return
	 */
	@RequestMapping(value = "/list")
	public String list(Model model) {
		List<BookType> list = bookTypeService.listAll();

		model.addAttribute("list", list);

		return "booktype/list";
	}

	/**
	 * Forward to edit.jsp and update the book type with id.
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/update")
	public String update(String id, Model model) {
		BookType bookType = bookTypeService.get(Integer.parseInt(id));

		model.addAttribute("bookType", bookType);

		return "booktype/edit";
	}

}
